import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/utils_dlog.dart';

import '../../global_easy_loading.dart';

class CodeFormField extends StatefulWidget {
  final FormFieldSetter<String>? onSaved;
  final Function()? onEditingComplete;
  final InputDecoration? decoration;
  final Function(String)? onChanged;
  // final Color? color;
  final Color? suffixColor;
  final FocusNode? focusNode;
  final Function getSmsCode;
  final String tagStr;

  const CodeFormField({
    Key? key,
    this.onSaved,
    this.decoration,
    // this.color = Colors.black,
    this.suffixColor = ThemeColor.primaryColor,
    this.focusNode,
    this.onChanged,
    this.onEditingComplete,
    required this.getSmsCode,
    required this.tagStr,
  }) : super(key: key);

  @override
  _CodeFormFieldState createState() => _CodeFormFieldState();
}

class _CodeFormFieldState extends State<CodeFormField> {
  Timer? _timer;
  int _maxCount = 0;

  bool isWaiting = false;

  //计时器
  void startCountTimer() {
    const timeout = const Duration(seconds: 1);
    _timer = Timer.periodic(timeout, (timer) {
      if (_maxCount < 1) {
        _timer?.cancel();
      } else {
        if (mounted) {
          setState(() {
            _maxCount -= 1;
          });
        }
      }
    });
  }

  void _captchaClick() async {
    bool res = false;
    isWaiting = true;
    if (mounted) {
      setState(() {});
    }
    res = await widget.getSmsCode();
    isWaiting = false;
    if (res) {
      appContext.storage
          .setInt(widget.tagStr, DateTime.now().millisecondsSinceEpoch);
      setState(() {
        _maxCount = 60;
      });
      startCountTimer();
    } else {
      if (mounted) {
        setState(() {});
      }
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    checkCountTimer();
  }

  checkCountTimer() {
    int timerEpoch = appContext.storage.getInt(widget.tagStr);
    int nowEpoch = DateTime.now().millisecondsSinceEpoch;
    if (nowEpoch - timerEpoch < 60 * 1000) {
      setState(() {
        _maxCount = (60 - (nowEpoch - timerEpoch) ~/ 1000);
      });
      // DLog(nowEpoch - timerEpoch);
      // DLog(_maxCount);
      startCountTimer();
    }
    // String cachePhone = appContext.storage.getString("login_phone") ?? '';
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    String hintText = S.of(context).enter_code;
    Widget suffixIcon = Container(
        // padding: EdgeInsets.only(
        //   top: 10,
        //   left: 0,
        //   right: 15,
        //   bottom: 0,
        // ),
        // color: Colors.amber,
        child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        GestureDetector(
            onTap: ClickUtils.debounce(() {
              if (_maxCount == 0 && isWaiting == false) {
                _captchaClick();
              }
            }),
            child: Container(
              margin: EdgeInsets.only(right: 15),
              child: isWaiting
                  ? const CupertinoActivityIndicator(
                      radius: 10,
                      color: ThemeColor.color979797,
                    )
                  : Text(
                      _maxCount > 0
                          ? S.current.resend_count_down(_maxCount)
                          // ? '${S.of(context).resend_count_down}($_maxCount)'
                          : S.of(context).send_code,
                      style: TextStyle(
                        color: widget.suffixColor,
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
            )),
      ],
    ));
    return TextFormField(
      enableInteractiveSelection: true,
      inputFormatters: [
        FilteringTextInputFormatter.deny(appContext.emojiRegexp)
      ],
      style: const TextStyle(
        color: Colors.black,
        fontSize: 14,
        // height: 1.5,
        // fontWeight: FontWeight.bold,
      ),
      onEditingComplete: widget.onEditingComplete,
      onChanged: widget.onChanged,
      cursorColor: ThemeColor.primaryColor,
      decoration: widget.decoration!.copyWith(
        hintText: hintText,
        suffixIcon: suffixIcon,
      ),
      focusNode: widget.focusNode,
      maxLength: 6,
      validator: (val) {
        if (val!.length != 6) {
          customShowToast(S.of(context).enter_6_code);
          return '';
        }
        return null;
      },
      onSaved: widget.onSaved,
      keyboardType: TextInputType.number,
      autocorrect: false,
    );
  }
}
